import re
from lxml import etree
from crawler.connection.tools import joint_url
from crawler.extractors import JsonpExtractor
from crawler.fields import ContainerField, JsonField

# sql = 'select * from selfridges_specifications'

# result = mysql_db.find(sql)
# result_list = list()
# for res in result:
#     item = {}
#     item['text'] = res[1]
#     item['url'] = res[2]
#     result_list.append(item)

__all__ = ['SelfRidgesMainExtractor', 'SelfRidgesDetailExtractor']


class SelfRidgesMainInfoExtractor(JsonpExtractor):
    container = ContainerField(json_selector='$.catalogEntryNavView[*]')
    spu_id = JsonField(json_selector='$.productId')
    brand = JsonField(json_selector='$.brandName')
    title = JsonField(json_selector='$.name')
    cost_price = JsonField(json_selector='$.price[0].lowestPrice')
    wages = JsonField(json_selector='$.price[0].lowestPrice')
    url = JsonField(json_selector='$.seoKey')
    color = JsonField(json_selector='$.previewAttribute')
    image_name = JsonField(json_selector='$.imageName')
    stock_color = JsonField(json_selector='$.previewAttribute')
    stock_spu_id = JsonField(json_selector='$.partNumber')


# class SelfRidgesDetailInfoExtractor(BaseExtractor):
#     product_des = TextField(
#         xpath_selector='//div[@class="c-tabs__copy"]/span/*', many=True)


class SelfRidgesMainExtractor:
    @classmethod
    def get_item(cls, response):
        return cls._extract(response)

    @classmethod
    def _extract(cls, response):
        task = response.meta['task']
        # sex = task['sex']
        # category = task['category']
        sex = task['info']['sex']
        category = task['info']['category']
        info_list = list()
        image_url = 'https://images.selfridges.com/is/image/selfridges/?req=set,json&imageset='
        for item in SelfRidgesMainInfoExtractor.get_items(response):
            info_dict = dict()
            info_dict['spu_id'] = item.spu_id
            # 品牌
            info_dict['brand'] = item.brand
            # 商标题
            info_dict['title'] = item.title
            # 品类
            info_dict['category'] = category
            # 性别
            info_dict['sex'] = sex
            # 图集 需要请求详情页
            info_dict['atlas'] = ''
            # 成本价
            info_dict['cost_price'] = item.cost_price
            # 公价 原价(没有打折的价格)对应公价
            info_dict['retail_price'] = item.wages
            # 货币单位
            info_dict['currency'] = 'HKD'
            info_dict['url'] = 'https://www.selfridges.com/HK/en/cat/' + item.url+'/#colour='+item.color
            # 规格 ，
            # if 'mens' in response.request.url and ''
            # info_dict['specifications'] = ''
            # 商品描述。详情页的
            info_dict['product_des'] = ''
            params = (
                ('option', 'SupplierColourName'),
                ('optionValue', item.stock_color),
                ('language', 'zh'),
            )
            stock_url = joint_url('https://www.selfridges.com/api/cms/ecom/v1/HK/en/stock/byId/' + item.stock_spu_id,
                                  params)
            info_dict['stock_url'] = stock_url
            # 尺寸库存
            info_dict['size_stock'] = ''
            info_dict['color'] = item.color
            # spu_id_upper = info_dict["url"].split('_')[-1].upper()
            # color = item.color.replace(" ", "").replace('/', '').replace('.', '').upper() if item.color else ''
            # if color:
            image_name = item.image_name.split('_M')[0]
            info_dict[
                'image_url'] = image_url + f'{{{image_name}_M,{image_name}_IMGSET,{image_name}_360,{image_name}_VID01-AVS}}&defaultImage=&handler=getImgSet'

            info_list.append(info_dict)

            # print(info_dict)
        return info_list


class SelfRidgesDetailExtractor:
    @classmethod
    def get_item(cls, response):
        return cls._extract(response)

    @classmethod
    def _extract(cls, response):
        # specifications_url = re.compile('SIZE_GUIDE_URL(.*?);', re.S).findall(response.text)
        # # specifications = 'nothing'
        # if specifications_url:
        #     specifications_url = 'https://www.selfridges.com' + specifications_url[0].replace('=', '') \
        #         .replace('"', "").replace("'", '').strip()
        #     for i in result_list:
        #         if i['url'] == specifications_url:
        #             specifications = i['text']
        # else:
        #     specifications = ''
        product_des = etree.HTML(response.text).xpath('//div[@class="c-tabs__copy"]/span/*//text()')
        return product_des
